// pages/workIndex/workIndex.js
import req from "../../utils/req";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lastFetchTime: "",
    left: "-50rpx",
    right: "-490rpx",
    empty: false,
    showWork: false,
    mask: true,
    percent: "80%",
    userInfo: wx.getStorageSync('userInfo'),
    // 缓存的数据
    bufferData:{},

    // 用于mask的弹窗的数据
    courseInfo: {
      name: "",
      tasks: [],
      demostrate: ""
    }
  },

  showWork: function (event) {
    let now = new Date();
    // console.log(date.toLocaleString());
    this.setData({
      showWork: true,
    });
    let id = event.currentTarget.dataset.id;
    for (let course of this.data.bufferData.courses) {
      if (course.courseId === id) {
        this.setData({
          "courseInfo.name": course.title,
          "courseInfo.tasks": [],
          "courseInfo.demostrate": course.course_demonstrate
        })
      }
    }
    // let res = await req("/")
    for (let task of this.data.bufferData.tasks) {
      if (id === parseInt(task.course.course_id)) {
        // console.log(this.data.courseInfo);
        for (let item of task.tasks) {
          let date = new Date(item.status.deadLine);
          if (date > now) {
            let hours = (date.getTime() - now.getTime()) / 1000 / 60 / 60;
            // console.log(hours);
            if (hours >= 120) {
              item["percent"] = "0%";
              item["bg"] = "#d7d9ff";
            } else if (hours < 120 && hours >= 0) {
              item["percent"] = (1 - hours / 120) * 100 + "%";
              item["bg"] = "#a1b6ff";
            } else {
              item["percent"] = "100%";
              item["bg"] = "#d1d1d1";
            }
          } else {
            item["percent"] = "100%";
            item["bg"] = "#d1d1d1";
          }
        }
        this.setData({
          "courseInfo.tasks": task.tasks,
        });
        // console.log(task.tasks);
      }
    }

  },

  close: function () {
    this.setData({
      showWork: false,
    });
  },
  goToWork: function (event) {
    wx.navigateTo({
      url: '/pages/homework/homework?id=' + event.currentTarget.dataset.id,
    })
  },
  goToMine: function () {
    wx.redirectTo({
      url: '/pages/mine/mine',
    })
  },
  fetchDataFromServer: async function() {
    let tasks = await req(`/tasks`);
    let status = [];
    for (let task of tasks) {
      status.push(parseInt(task.course.course_id));
    }
    let courses = await req(`/courses`);
    for (let course of courses) {
      // courserId是number
      // console.log(typeof course.courseId);
      if (status.indexOf(course.courseId) >= 0) {
        course["status"] = 1;
      } else {
        course["status"] = 0;
      }
    }
    let left = 540 * tasks.length / courses.length;
    let right = 540 - left;

    let bufferData = {
      courses: courses,
      tasks: tasks,
      right: -right + "rpx",
      left: -left + "rpx",
      status: status,
      mask: false,
    }
    wx.setStorageSync('bufferData', bufferData)

    const now = new Date();
    return now.toLocaleDateString() + ' ' + now.toLocaleTimeString();
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })

    /**数据只会在初始的情况下加载一次 */
    let lastFetchTime = wx.getStorageSync('lastFetchTime')
    console.log('lastFetchTime', lastFetchTime)

    if (!lastFetchTime) {
      let fetchTime = await this.fetchDataFromServer()
      wx.setStorageSync('lastFetchTime', fetchTime)
    } 

    this.setData({
      lastFetchTime: wx.getStorageSync('lastFetchTime'),
      bufferData: wx.getStorageSync('bufferData')
    })
    
    wx.hideLoading();

  },

})